/*
 * 存储配置统一性验证和修复工具
 * 确保 Upload 和 CloudStorage 配置保持一致性
 */

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace JGSY.CMS.LowCode.Platform.Infrastructure.Configuration
{
    /// <summary>
    /// 存储配置统一性管理器
    /// </summary>
    public class StorageConfigurationUnifier
    {
        private readonly IConfiguration _configuration;
        private readonly ILogger<StorageConfigurationUnifier> _logger;

        public StorageConfigurationUnifier(
            IConfiguration configuration,
            ILogger<StorageConfigurationUnifier> logger)
        {
            _configuration = configuration;
            _logger = logger;
        }

        /// <summary>
        /// 验证配置一致性
        /// </summary>
        public ConfigValidationResult ValidateConfigurationConsistency()
        {
            var result = new ConfigValidationResult();
            
            try
            {
                var uploadConfig = _configuration.GetSection("Upload");
                var cloudStorageConfig = _configuration.GetSection("CloudStorage");
                
                // 检查路径一致性
                var uploadLocalPath = uploadConfig.GetSection("Local:RootPath").Value;
                var cloudStorageLocalPath = cloudStorageConfig.GetSection("Local:RootPath").Value;
                
                if (uploadLocalPath != cloudStorageLocalPath)
                {
                    result.AddError("Upload.Local.RootPath 和 CloudStorage.Local.RootPath 路径不一致", 
                        $"Upload: {uploadLocalPath}, CloudStorage: {cloudStorageLocalPath}");
                }

                // 检查BaseUrl一致性
                var uploadBaseUrl = uploadConfig.GetSection("Local:BaseUrl").Value;
                var cloudStorageBaseUrl = cloudStorageConfig.GetSection("Local:BaseUrl").Value;
                
                if (uploadBaseUrl != cloudStorageBaseUrl)
                {
                    result.AddError("Upload.Local.BaseUrl 和 CloudStorage.Local.BaseUrl 不一致",
                        $"Upload: {uploadBaseUrl}, CloudStorage: {cloudStorageBaseUrl}");
                }

                // 检查文件类型配置一致性
                var uploadExtensions = uploadConfig.GetSection("AllowedExtensions").Get<string[]>();
                var cloudStorageExtensions = cloudStorageConfig.GetSection("AllowedExtensions").Get<string[]>();
                
                if (!AreArraysEqual(uploadExtensions, cloudStorageExtensions))
                {
                    result.AddWarning("Upload.AllowedExtensions 和 CloudStorage.AllowedExtensions 不一致");
                }

                // 检查最大文件大小一致性
                var uploadMaxSize = uploadConfig.GetValue<long>("MaxFileSize");
                var cloudStorageMaxSize = cloudStorageConfig.GetValue<long>("MaxFileSize");
                
                if (uploadMaxSize != cloudStorageMaxSize)
                {
                    result.AddWarning("Upload.MaxFileSize 和 CloudStorage.MaxFileSize 不一致",
                        $"Upload: {uploadMaxSize}, CloudStorage: {cloudStorageMaxSize}");
                }

                _logger.LogInformation("配置一致性验证完成。错误: {ErrorCount}, 警告: {WarningCount}", 
                    result.Errors.Count, result.Warnings.Count);
                
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "配置一致性验证失败");
                result.AddError("配置验证异常", ex.Message);
                return result;
            }
        }

        /// <summary>
        /// 获取统一的存储配置
        /// 优先使用 CloudStorage 配置，如果不存在则使用 Upload 配置
        /// </summary>
        public UnifiedStorageConfiguration GetUnifiedStorageConfiguration()
        {
            var cloudStorageConfig = _configuration.GetSection("CloudStorage");
            var uploadConfig = _configuration.GetSection("Upload");
            
            var config = new UnifiedStorageConfiguration
            {
                // 优先使用 CloudStorage 的配置
                StorageType = cloudStorageConfig.GetValue<string>("StorageType") ?? uploadConfig.GetValue<string>("StorageType") ?? "Local",
                MaxFileSize = cloudStorageConfig.GetValue<long>("MaxFileSize") > 0 ? 
                    cloudStorageConfig.GetValue<long>("MaxFileSize") : uploadConfig.GetValue<long>("MaxFileSize"),
                AllowedExtensions = cloudStorageConfig.GetSection("AllowedExtensions").Get<string[]>() ?? 
                    uploadConfig.GetSection("AllowedExtensions").Get<string[]>() ?? new string[0],
                ImageExtensions = cloudStorageConfig.GetSection("ImageExtensions").Get<string[]>() ?? 
                    uploadConfig.GetSection("ImageExtensions").Get<string[]>() ?? new string[0],
                
                // 本地存储配置
                Local = new UnifiedLocalStorageConfiguration
                {
                    Enabled = cloudStorageConfig.GetValue<bool>("Local:Enabled", true),
                    RootPath = cloudStorageConfig.GetValue<string>("Local:RootPath") ?? 
                        uploadConfig.GetValue<string>("Local:RootPath") ?? "wwwroot/uploads",
                    BaseUrl = cloudStorageConfig.GetValue<string>("Local:BaseUrl") ?? 
                        uploadConfig.GetValue<string>("Local:BaseUrl") ?? "/uploads",
                    TempPath = cloudStorageConfig.GetValue<string>("Local:TempPath") ?? 
                        uploadConfig.GetValue<string>("Local:TempPath") ?? "wwwroot/uploads/temp",
                    ThumbnailPath = cloudStorageConfig.GetValue<string>("Local:ThumbnailPath") ?? 
                        uploadConfig.GetValue<string>("Local:ThumbnailPath") ?? "wwwroot/uploads/thumbnails",
                    CreateDateFolders = cloudStorageConfig.GetValue<bool>("Local:CreateDateFolders", true),
                    GenerateThumbnails = cloudStorageConfig.GetValue<bool>("Local:GenerateThumbnails", true),
                    EnableVirusScan = cloudStorageConfig.GetValue<bool>("Local:EnableVirusScan", false),
                    EnableFileDeduplication = cloudStorageConfig.GetValue<bool>("Local:EnableFileDeduplication", true)
                }
            };

            return config;
        }

        /// <summary>
        /// 自动修复配置不一致问题
        /// </summary>
        public async Task<bool> AutoFixConfigurationAsync(string configFilePath)
        {
            try
            {
                var validationResult = ValidateConfigurationConsistency();
                
                if (!validationResult.HasIssues())
                {
                    _logger.LogInformation("配置已经一致，无需修复");
                    return true;
                }

                _logger.LogInformation("开始自动修复配置不一致问题...");
                
                // 读取配置文件
                var jsonContent = await File.ReadAllTextAsync(configFilePath);
                var jsonObject = JObject.Parse(jsonContent);
                
                // 获取统一配置
                var unifiedConfig = GetUnifiedStorageConfiguration();
                
                // 更新 Upload 配置
                UpdateUploadConfiguration(jsonObject, unifiedConfig);
                
                // 更新 CloudStorage 配置
                UpdateCloudStorageConfiguration(jsonObject, unifiedConfig);
                
                // 保存配置文件
                var updatedJson = jsonObject.ToString(Formatting.Indented);
                await File.WriteAllTextAsync(configFilePath, updatedJson);
                
                _logger.LogInformation("配置修复完成，已保存到: {ConfigFilePath}", configFilePath);
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "配置自动修复失败");
                return false;
            }
        }

        private void UpdateUploadConfiguration(JObject jsonObject, UnifiedStorageConfiguration config)
        {
            var uploadSection = jsonObject["Upload"] ?? new JObject();
            
            uploadSection["StorageType"] = config.StorageType;
            uploadSection["MaxFileSize"] = config.MaxFileSize;
            uploadSection["AllowedExtensions"] = JArray.FromObject(config.AllowedExtensions);
            uploadSection["ImageExtensions"] = JArray.FromObject(config.ImageExtensions);
            uploadSection["CreateDateFolders"] = config.Local.CreateDateFolders;
            uploadSection["GenerateThumbnails"] = config.Local.GenerateThumbnails;
            
            var localSection = uploadSection["Local"] ?? new JObject();
            localSection["RootPath"] = config.Local.RootPath;
            localSection["BaseUrl"] = config.Local.BaseUrl;
            localSection["TempPath"] = config.Local.TempPath;
            localSection["ThumbnailPath"] = config.Local.ThumbnailPath;
            
            uploadSection["Local"] = localSection;
            jsonObject["Upload"] = uploadSection;
        }

        private void UpdateCloudStorageConfiguration(JObject jsonObject, UnifiedStorageConfiguration config)
        {
            var cloudSection = jsonObject["CloudStorage"] ?? new JObject();
            
            cloudSection["StorageType"] = config.StorageType;
            cloudSection["MaxFileSize"] = config.MaxFileSize;
            cloudSection["AllowedExtensions"] = JArray.FromObject(config.AllowedExtensions);
            cloudSection["ImageExtensions"] = JArray.FromObject(config.ImageExtensions);
            
            var localSection = cloudSection["Local"] ?? new JObject();
            localSection["Enabled"] = config.Local.Enabled;
            localSection["RootPath"] = config.Local.RootPath;
            localSection["BaseUrl"] = config.Local.BaseUrl;
            localSection["TempPath"] = config.Local.TempPath;
            localSection["ThumbnailPath"] = config.Local.ThumbnailPath;
            localSection["CreateDateFolders"] = config.Local.CreateDateFolders;
            localSection["GenerateThumbnails"] = config.Local.GenerateThumbnails;
            localSection["EnableVirusScan"] = config.Local.EnableVirusScan;
            localSection["EnableFileDeduplication"] = config.Local.EnableFileDeduplication;
            
            cloudSection["Local"] = localSection;
            jsonObject["CloudStorage"] = cloudSection;
        }

        private bool AreArraysEqual(string[]? array1, string[]? array2)
        {
            if (array1 == null && array2 == null) return true;
            if (array1 == null || array2 == null) return false;
            if (array1.Length != array2.Length) return false;
            
            return array1.OrderBy(x => x).SequenceEqual(array2.OrderBy(x => x));
        }
    }

    /// <summary>
    /// 配置验证结果
    /// </summary>
    public class ConfigValidationResult
    {
        public List<ConfigurationIssue> Errors { get; } = new List<ConfigurationIssue>();
        public List<ConfigurationIssue> Warnings { get; } = new List<ConfigurationIssue>();
        
        public void AddError(string message, string? details = null)
        {
            Errors.Add(new ConfigurationIssue { Message = message, Details = details, Severity = "Error" });
        }
        
        public void AddWarning(string message, string? details = null)
        {
            Warnings.Add(new ConfigurationIssue { Message = message, Details = details, Severity = "Warning" });
        }
        
        public bool HasIssues() => Errors.Count > 0 || Warnings.Count > 0;
        public bool HasErrors() => Errors.Count > 0;
    }

    /// <summary>
    /// 配置问题描述
    /// </summary>
    public class ConfigurationIssue
    {
        public string Message { get; set; } = string.Empty;
        public string? Details { get; set; }
        public string Severity { get; set; } = "Info";
    }

    /// <summary>
    /// 统一存储配置模型
    /// </summary>
    public class UnifiedStorageConfiguration
    {
        public string StorageType { get; set; } = "Local";
        public long MaxFileSize { get; set; } = 52428800;
        public string[] AllowedExtensions { get; set; } = new string[0];
        public string[] ImageExtensions { get; set; } = new string[0];
        public UnifiedLocalStorageConfiguration Local { get; set; } = new UnifiedLocalStorageConfiguration();
    }

    /// <summary>
    /// 统一本地存储配置模型
    /// </summary>
    public class UnifiedLocalStorageConfiguration
    {
        public bool Enabled { get; set; } = true;
        public string RootPath { get; set; } = "wwwroot/uploads";
        public string BaseUrl { get; set; } = "/uploads";
        public string TempPath { get; set; } = "wwwroot/uploads/temp";
        public string ThumbnailPath { get; set; } = "wwwroot/uploads/thumbnails";
        public bool CreateDateFolders { get; set; } = true;
        public bool GenerateThumbnails { get; set; } = true;
        public bool EnableVirusScan { get; set; } = false;
        public bool EnableFileDeduplication { get; set; } = true;
    }
}
